package top.infopub.mgr.cap.service.impl;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import top.infopub.enums.cap.CapProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.cap.dao.*;
import top.infopub.mgr.cap.domain.LookInfoDomain;
import top.infopub.mgr.cap.domain.SetupFinDomain;
import top.infopub.mgr.cap.dto.SetupFinDto;
import top.infopub.mgr.cap.service.SetupFinService;
import top.infopub.mgr.cap.vo.LookInfoBeginVo;
import top.infopub.mgr.cap.vo.SetupFinVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.cnst.FlowTemplateEnum;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.mkt.dao.ProjectInfoDao;
import top.infopub.mgr.sg.dao.CitySurveyDao;
import top.infopub.model.cap.*;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import top.infopub.model.mkt.ProjectInfo;
import top.infopub.model.sg.CitySurvey;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

@Service
public class SetupFinServiceImpl extends GenericServiceImpl<SetupFin, String> implements
		SetupFinService {

	@Autowired
	private SetupFinDao setupFinDao;

	@Autowired
	private SetupFinAimDao setupFinAimDao;

	@Autowired
	private SetupFinAttDao setupFinAttDao;

	@Autowired
	private SetupFinCostDao setupFinCostDao;

	@Autowired
	private SetupFinNodeDao setupFinNodeDao;

	@Autowired
    private WsFlowProcessService wsFlowProcess;

	@Autowired
    private SetupFinancialDao setupFinancialDao;

	@Autowired
    private ProjectInfoDao projectInfoDao;
	@Autowired
    private CitySurveyDao citySurveyDao;

	@Autowired
    private LookInfoBankDao lookInfoBankDao;

	@Autowired
    private CapProcessManageServiceImpl capProcessManageService;

	@Override
	public GenericDao<SetupFin, String> getDao() {
		return setupFinDao;
	}

    @Override
    public Page<LookInfoDomain> selectByDomainWhere(Page<LookInfoDomain> page,
                                                    LookInfoBeginVo lookInfoBeginVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<LookInfoDomain>)setupFinDao.selectByDomainWhere(lookInfoBeginVo);
    }

    @Override
    public Page<SetupFinDomain> selectMyCheckByDomainWhere(Page<SetupFinDomain> page,
                                                           SetupFinVo setupFinVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<SetupFinDomain>)setupFinDao.selectMyCheckByDomainWhere(setupFinVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSetupFin(SetupFin setupFin, List<SetupFinAim> setupFinAims,
                             List<SetupFinAtt> setupFinAtts, List<SetupFinCost> setupFinCosts,
                             List<SetupFinNode> setupFinNodes) {
        //执行新增
        //添加融资立项记录
        setupFinDao.insertById(setupFin);

        //添加融资立项工作目标记录
        if(CollectionUtils.isNotEmpty(setupFinAims)){
            setupFinAimDao.insertByBatch(setupFinAims);
        }

        //添加融资立项附件
        if(CollectionUtils.isNotEmpty(setupFinAtts)){
            setupFinAttDao.insertByBatch(setupFinAtts);
        }

        //添加融资立项费用明细
        if(CollectionUtils.isNotEmpty(setupFinCosts)){
            setupFinCostDao.insertByBatch(setupFinCosts);
        }

        //添加融资立项工作节点
        if(CollectionUtils.isNotEmpty(setupFinNodes)){
            setupFinNodeDao.insertByBatch(setupFinNodes);
        }

        // 注意 这里根据不同的业务分支判断条件 获得不同enum
        FlowTemplateEnum templateEnum = FlowTemplateEnum.CAP_SETUP_FIN;
        // 处理工作流数据
        wsFlowProcess.launch(templateEnum, setupFin.getId(), setupFin.getProcessId(), null);

    }

    @Override
    public SetupFin selectById(String id){
        return setupFinDao.selectById(id);
    }

    @Override
    public List<SetupFin> selectAll(String proCode,String codes) {
        return setupFinDao.selectAll(proCode,codes);
    }

    @Override
    public RspVo queryDetailById(String id) {

        SetupFinDto setupFinDto = new SetupFinDto();
	    //融资立项信息
        SetupFin setupFin = setupFinDao.selectById(id);
        setupFinDto.setProCode(setupFin.getProCode());
        setupFinDto.setProName(setupFin.getProName());
        setupFinDto.setId(id);
        ProjectInfo byProCode = projectInfoDao.findByProCode(setupFin.getProCode());
        if (byProCode!=null){
            setupFinDto.setProName(byProCode.getProName());
            setupFinDto.setRefProvinceId(byProCode.getRefProvinceId());
            setupFinDto.setRefCityId(byProCode.getRefCityId());
            setupFinDto.setRefAreaId(byProCode.getRefAreaId());
        }else{
            //根据城市调研信息查找地址
            CitySurvey citySurvey = citySurveyDao.selectByPrimaryKey(setupFin.getSgCityId());
            setupFinDto.setRefProvinceId(citySurvey.getRefProvinceId());
            setupFinDto.setRefCityId(citySurvey.getRefCityId());
            setupFinDto.setRefAreaId(citySurvey.getRefAreaId());
        }
        //金融信息
        List<SetupFinancial> setup = setupFinancialDao.selectByFinId(id);
        setupFinDto.setSetupFinancials(setup);

        return RspVo.getSuccessResponse(setupFinDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo saveAll(AuthorizationVO userDtl, SetupFin setupFin1, List<SetupFinancial> setupFinancials, Integer submitType,String bodyStr) {

        SetupFin selectById = setupFinDao.selectById(setupFin1.getId());
        if (selectById!=null &&
                StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(),selectById.getProcessStatus())
                || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(),selectById.getProcessStatus())
        ){
            return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
        }
	    //处理主表信息
        if (StringUtils.isNotBlank(setupFin1.getId())){//修改
            SetupFin setupFin2 = new SetupFin();
            setupFin2.setUptBy(userDtl.getId());
            setupFin2.setUptTime(new Date());
            //处理金融信息
            setupFinancialDao.deleteByFinId(setupFin1.getId());
            for (SetupFinancial setupFinancial : setupFinancials) {
                 setupFinancial.setFinId(setupFin1.getId());
                 if (StringUtils.isBlank(setupFin2.getFinancingType())){
                     setupFin2.setId(setupFin1.getId());
                     setupFin2.setFinancingType(setupFinancial.getFinancingType());
                 }
            }
            //将第一个金融机构的融资方式添加到主表中
            setupFinDao.update(setupFin2);
            setupFinancialDao.insertBatch(setupFinancials);
        }else{ //新增
            setupFin1.setId(IdFactory.getUUIDUpper());
            List<LookInfoBank> lookInfoBank = new LinkedList<>();
            if (setupFinancials.size()>0){
            for (SetupFinancial setupFinancial : setupFinancials) {
                setupFinancial.setFinId(IdFactory.getUUIDUpper());

                //立项新增 对接银行
                LookInfoBank lookInfoBank1 = new LookInfoBank();
                lookInfoBank1.setId(IdFactory.getUUIDUpper());
                lookInfoBank1.setDockBank(setupFinancial.getFinOrg());
                lookInfoBank1.setBankName(setupFinancial.getBankName());
                lookInfoBank1.setProCode(setupFin1.getProCode());
                lookInfoBank.add(lookInfoBank1);

                setupFinancial.setFinOrg(lookInfoBank1.getId());
                setupFinancial.setFinId(setupFin1.getId());
                if (StringUtils.isBlank(setupFin1.getFinancingType())){
                    setupFin1.setFinancingType(setupFinancial.getFinancingType());
                }
            }
        }
            lookInfoBankDao.insertByBatch(lookInfoBank);
            setupFinDao.insertById(setupFin1);
            setupFinancialDao.insertBatch(setupFinancials);
      }
        if (submitType==2){
            capProcessManageService.sendProcess(CapProcessDetailTypeEnum.PRO_NODE_TYPE4,bodyStr,setupFin1.getId(),setupFin1.getProCode(),userDtl);
        }
        return RspVo.getSuccessResponse();
	}

    @Override
    public SetupFin selectByProName(String proName) {
        return setupFinDao.selectByProName(proName);
    }
}
